﻿using CIS.Client.Common.HttpRequestHelper;
using CIS.Client.Modules.Operation.Models;
using CIS.Common.Dtos.ClientDtos;
using CIS.Common.Enums;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CIS.Client.Modules.Operation.ViewModels
{
    public class PPIDAddViewModel : BindableBase,IDialogAware
    {
        private readonly HttpRequestClient _httpRequest;

        public PPIDAddViewModel(HttpRequestClient httpRequestClient)
        {
            _httpRequest = httpRequestClient;
            Init();
        }

        #region 属性
        private string? ppid;
        /// <summary>
        /// 绑定 PPID
        /// </summary>
        public string? PPID
        {
            get { return ppid; }
            set { ppid = value; }
        }

        private string? selectOperationName;
        /// <summary>
        /// 选定的 OperationName
        /// </summary>
        public string? SelectOperationName
        {
            get { return selectOperationName; }
            set { selectOperationName = value; }
        }

        private bool selectMixRunFlag;
        /// <summary>
        /// 选定的 Mix Run Flag
        /// </summary>
        public bool SelectMixRunFlag
        {
            get { return selectMixRunFlag; }
            set { selectMixRunFlag = value; }
        }

        private string selectUnit;
        /// <summary>
        /// 选定的值 Unit ID
        /// </summary>
        public string SelectUnit
        {
            get { return selectUnit; }
            set 
            { 
                selectUnit = value;
                GetUnitRecipeNo();
            }
        }

        private List<string>? operationNames;
        /// <summary>
        /// Operation Name 下拉框绑定的值
        /// </summary>
        public List<string>? OperationNames
        {
            get { return operationNames; }
            set { operationNames = value; }
        }

        private List<bool> mixRunFlags;
        /// <summary>
        /// Mix Run Flag 下拉框绑定的值
        /// </summary>
        public List<bool> MixRunFlags
        {
            get { return mixRunFlags; }
            set { mixRunFlags = value; }
        }

        private List<string>? units;
        /// <summary>
        /// Unit Name 下拉框绑定的值
        /// </summary>
        public List<string>? Units
        {
            get { return units; }
            set { units = value; }
        }

        private List<UnitRecipeModel>? unitRecipes;
        /// <summary>
        /// Unit Name 下拉框绑定的值
        /// </summary>
        public List<UnitRecipeModel>? UnitRecipes
        {
            get { return unitRecipes; }
            set 
            { 
                unitRecipes = value; 
                RaisePropertyChanged(nameof(UnitRecipes)); 
            }
        }

        private List<PPIDMappingClientDto> ppidMappings;
        /// <summary>
        /// 绑定 PPID 与设备 Recipe 绑定列表
        /// </summary>
        public List<PPIDMappingClientDto> PPIDMappings
        {
            get { return ppidMappings; }
            set { ppidMappings = value; }
        }
        #endregion

        #region 命令
        private DelegateCommand? _confirmCommand;
        /// <summary>
        /// 确定按钮命令
        /// </summary>
        public DelegateCommand? ConfirmCommand
        {
            get { return _confirmCommand ?? new DelegateCommand(ConfirmFunction); }
        }

        private DelegateCommand? _closeCommand;
        /// <summary>
        /// 取消按钮命令
        /// </summary>
        public DelegateCommand? CloseCommand
        {
            get { return _closeCommand ?? new DelegateCommand(CloseFunction); }
        }

        private List<RecipeClientDto> RecipeList { get; set; }
        #endregion

        #region 方法
        /// <summary>
        /// 初始化
        /// </summary>
        private async void Init()
        {
            OperationNames = new List<string>()
            {
                "Normal",
                "MQC_Flow"
            };
            MixRunFlags = new List<bool>()
            {
                true,
                false
            };
            PPIDMappings = new List<PPIDMappingClientDto>()
            {
                new PPIDMappingClientDto()
                {
                    SourceId = "3AFS12-USC",
                    RecipeList = new List<int>()
                },
                new PPIDMappingClientDto()
                {
                    SourceId = "3AFS12-SPU",
                     RecipeList = new List<int>(),
                }
            };
            Units = new List<string>();
            HttpRequest request = new HttpRequest();
            request.Route = "Unit/GetUnits";
            RequestResult result = await _httpRequest.SendGetAsync(request);
            var units = JsonConvert.DeserializeObject<List<UnitClientDto>>(Convert.ToString(result.Data));
            foreach(var item in units)
            {
                if(item.Category == EquipmentType.Process)
                    Units.Add(item.QualifiedLocationId);
            }

            RecipeList= new List<RecipeClientDto>();
            HttpRequest request1 = new HttpRequest();
            request1.Route = "ProcessProgram/GetRecipes";
            RequestResult result1= await _httpRequest.SendGetAsync(request1);
            RecipeList = JsonConvert.DeserializeObject<List<RecipeClientDto>>(Convert.ToString(result1.Data));

            foreach(var item in ppidMappings)
            {
                var recipes = RecipeList.FindAll(r => r.SourceId == item.SourceId).OrderBy(r=>r.RecipeNo);
                foreach(var recipe in recipes)
                {
                    item.RecipeList.Add(recipe.RecipeNo);
                }                
            }
        }

        /// <summary>
        /// 获取 Unit Recipe List
        /// </summary>
        private void GetUnitRecipeNo()
        {
            UnitRecipes = new List<UnitRecipeModel>();
            var recipes = RecipeList.FindAll(x =>x.SourceId == SelectUnit).OrderBy(c=>c.RecipeNo);
            foreach(var item in recipes)
            {
                UnitRecipeModel recipeModel = new UnitRecipeModel();
                recipeModel.RecipeNo = item.RecipeNo;
                recipeModel.RecipeVersion = item.Version;
                recipeModel.ParameterCount = item.Parameters.Count();
                UnitRecipes.Add(recipeModel);
            }
        }

        /// <summary>
        /// 确定按钮处理逻辑
        /// </summary>
        private async void ConfirmFunction()
        {
            HttpRequest request = new HttpRequest();
            request.Route = "ProcessProgram/AddProcessProgram";
            ProceeProgramClientDto para = new ProceeProgramClientDto();
            para.PPID = this.PPID;
            para.OperationName = this.SelectOperationName;
            para.MixRunFlag = this.SelectMixRunFlag;
            para.PPIDRecipeMappingsClient = this.PPIDMappings;

            request.Parameters = JsonConvert.SerializeObject(para);
            RequestResult result = await _httpRequest.SendPostAsync(request);
            if (result.IsSuccess)
            {
                //var reply = JsonConvert.DeserializeObject<PortControlCommandDto>(result.Data.ToString());
                DialogParameters dialogParameters = new DialogParameters(result.Message);
                DialogResult returnResult = new DialogResult(ButtonResult.OK, dialogParameters);     
                this.RequestClose?.Invoke(returnResult);
            }
            else
            {
                DialogParameters dialogParameters = new DialogParameters()
                {
                    {"Message",result.Message }
                };
                DialogResult returnResult = new DialogResult(ButtonResult.No, dialogParameters);
                this.RequestClose?.Invoke(returnResult);
            }
        }

        /// <summary>
        /// 取消按钮处理逻辑
        /// </summary>
        private void CloseFunction()
        {
            DialogResult result = new DialogResult(ButtonResult.Cancel);
            RequestClose?.Invoke(result);
        }
        #endregion

        #region DialogAware 相关
        public string Title { get; set; } = "AddMapping";

        public event Action<IDialogResult>? RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }

        #endregion
    }
}
